import {Component, Renderer2} from '@angular/core';
import {ICellEditorAngularComp} from '@ag-grid-community/angular';
import { EditorDateComponent } from '@shared/ag-grid-ext/cell-editors/editor-date.component';
import { GridConfigService } from '@core/config/grid-config.service';
import { EditorTimeComponent } from '@shared/ag-grid-ext/cell-editors/editor-time.component';
import { dateFormat } from '../../../utils/utils';
import {ApesModalService} from "@shared/apes/modal";

export function timeFormatter(params){
  let value: any;
  if(params.value){
    value = dateFormat("HH:mm",new Date(params.value));
  }
  return value;
}

function operationCellRenderer(params) {
  if (params.node.hovered) {
    return `<div class="ag-editor-button">
                  <i class="anticon anticon-plus" id="add"></i>
                  <i class="anticon anticon-delete" id="del"></i>
               </div>`;
  }
  return params.rowIndex + 1;
}
@Component({
  selector: 'apes-cell-time-range',
  template: `
     <ag-grid-angular
        #agGrid
        style="width: 500px; height: 200px;"
        id="myGrid"
        class="ag-theme-balham"
        [columnDefs]="columnDefs"
        [rowData]="rowData"
        [localeText]="localeText"
        [frameworkComponents]="frameworkComponents"
        [stopEditingWhenGridLosesFocus]="false"
        [enterMovesDownAfterEdit]="true"
        [enterMovesDown]="false"
        [tabToNextCell]="tabToNextCell"
        suppressLoadingOverlay="true"
        suppressNoRowsOverlay="true"
        singleClickEdit="true"
        (cellMouseOver)="onCellMouseOver($event)"
        (cellMouseOut)="onCellMouseOut($event)"
        (cellMouseDown)="onCellMouseDown($event)"
        (gridReady)="onGridReady($event)">
      </ag-grid-angular>
     `,
  styles: []
})
export class EditorTimeRangeComponent implements ICellEditorAngularComp {
  inputValue: any;
  params: any;
  ctx: any;
  localeText:any;
  selectData: any;
  valid:any;

  private gridApi;
  private gridColumnApi;
  columnDefs;
  rowData;  frameworkComponents;
  constructor( protected gridConfigService: GridConfigService,private modalService: ApesModalService,private renderer: Renderer2,) {
    this.localeText = gridConfigService.getLocaleText();
    this.valid = true;
    this.columnDefs = [
      {
        headerName: '序号',
        editable: false,
        field:'operation',
        pinned:'left',
        suppressMenu: true,
        cellRenderer: operationCellRenderer,
      },
      {
        headerName: "课程日期",
        field: "courseDate",
        editable: true,
        cellEditor:"date"
      },
      {
        headerName: "开课时段",
        field: "courseStateTime",
        editable: true,
        cellEditor:"time",
        valueFormatter:timeFormatter
      },
      {
        headerName: "开课结束",
        field: "courseEndTime",
        editable: true,
        cellEditor:"time",
        valueFormatter:timeFormatter
      }
    ];

    this.frameworkComponents = {
      date: EditorDateComponent,
      time: EditorTimeComponent
    };

    this.tabToNextCell = this.tabToNextCell.bind(this);
  }

  agInit(params: any): void {
    this.params = params;
    if (params.value){
      this.rowData = params.value;
    }else{
      this.rowData=[{},{},{},{},{},{}];
    }

  }

  ngAfterViewInit() {

  }
  isPopup(): boolean {
    return true;
  }

  getValue(): any {
    let result;
    if (!this.rowData) {
      result = '';
      this.params.value = '';
    } else {
      result = this.rowData;
      this.params.value =  this.rowData;
    }
    return result;
  }
  tabToNextCell(params) {
    this.preventDefaultAndPropagation(event);
    let previousCell = params.previousCellDef;
    let lastRowIndex = previousCell.rowIndex;
    let nextRowIndex = params.backwards ? lastRowIndex - 1 : lastRowIndex + 1;
    let renderedRowCount = this.gridApi.getModel().getRowCount();
    if (nextRowIndex < 0) {
      nextRowIndex = 0;
    }
    if (nextRowIndex >= renderedRowCount) {
      nextRowIndex = renderedRowCount + 1;
    }
    let result = {
      rowIndex: nextRowIndex,
      column: previousCell.column,
      floating: previousCell.floating
    };
    return result;
  }

  //  onKeyDown(event): void {
  //    let key = event.which || event.keyCode;
  //    if (key == 9) {
  //      // tab
  //      this.preventDefaultAndPropagation(event);
  //    }
  // }
  onGridReady(params) {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;

    params.api.sizeColumnsToFit();
  }
  private preventDefaultAndPropagation(event) {
    event.preventDefault();
    event.stopPropagation();
  }

  onCellMouseOver(params) {
    params.node.hovered = true;
    params.event.preventDefault();
    this.gridApi.refreshCells({ force: true,columns:['operation'] });
    this.editorButton();
  }

  onCellMouseOut(params) {
    params.node.hovered = false;
    params.event.preventDefault();
    this.gridApi.refreshCells({ force: true,columns:['operation'] });
  }

  editorButton(){
    let editorBtn = document.querySelector('.ag-editor-button');
    if(editorBtn == null) return;
    let addBtn = editorBtn.children[0];
    if(this.valid == true){
      this.renderer.setStyle(editorBtn, 'display', 'block');
      if(this.valid == true){
        this.renderer.setStyle(addBtn, 'display', 'inline-block');
      }
    }
  }

  onCellMouseDown(params) {
    // console.log(params);
    if (params.node.hovered == true) {
      if (params.event.target.id == 'add') {
        if(this.valid == true){
          this.onInsertRow();
        }
      } else if (params.event.target.id == 'del') {
        this.selectData = params;
        this.onRemoveSelected();
      }
    }
    // this.preventDefaultAndPropagation(event);
  }

  /**
   * 功能：插入行
   * @param params
   */
  onInsertRow() {
    const newItem = {};
    this.addRow(newItem);
  }
  addRow(newItem) {
    this.gridApi.applyTransaction({
      add: [newItem],
    });

   // let params = { data: newItem };

  }


  /**
   * 功能：删除行数据
   */
  onRemoveSelected() {
    let row = this.selectData.data;
    this.modalService.confirm({
      apesTitle: '<i>是否删除当前在编辑的数据?</i>',
      apesOnOk: () => this.deleteRow(row),
    });
  }

  deleteRow(row) {
    try {
      let result = this.gridApi.updateRowData({ remove: [row] });
      if (result.remove.length === 0) return;
      this.preventDefaultAndPropagation(event);
    } catch (e) {
      return;
    }
  }
}
